﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Lib.Paging;
using SDT.Lib.Common;
using System.IO;
using SDT.Lib.Helpers;
using SDT.Admin.Properties;
using SDT.Model;
using SDT.Admin.ViewModels;
namespace SDT.Admin.Controllers
{
  //	[RoleHelper(Roles = RoleSystem.Banner)]
    public class BannerController : Controller
    {
        /// <summary>
        /// Created by: Vietlv
        /// Created date: 08/07/2011
        /// Description: Manage Banner - Class Banner controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Banner/ Index(int? Page)

        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null) page = 1;
                    string order = UserState.getUserStateFromRequest("banner.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("banner.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("banner.CatID", "CatID", 0));

                    int currentPub = Convert.ToInt32(UserState.getUserStateFromRequest("banner.PubStatus", "PubStatus", 0));
                    string keyword = UserState.getUserStateFromRequest("banner.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("banner.pageSize", "PageSize", 20).ToString());


                    var banner = eDataContext.Banners     
                        .Where(a => currentPub > 0 ? a.PubYN == (currentPub == 1 ? true : false) : true)
                        .Where(a => (string.IsNullOrEmpty(keyword) ? true :
                            (a.Name.ToLower().Contains(keyword.ToLower().Trim()))))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    var postion = eDataContext.Positions.ToList();
                    var menu = eDataContext.Menus.ToList();
                    var pubs = Utils.StringToDictionary(Settings.Default.BannerPubStatus.ToString(), ",");

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new BannerIndexViewModel
                    {
                        Banners = banner,
                        PubStatus = pubs,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.BannerImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Banner/Details(int id)

        public ActionResult Details(int id)
        {
            var banner = eDataContext.Banners.Where(a => a.ID == id).SingleOrDefault();
            var imgRootUrl = Settings.Default.SiteRootUrl + Settings.Default.BannerImagePreviewUrlPrefix;
            var flashRootUrl = Settings.Default.SiteRootUrl + Settings.Default.BannerFlashPreviewUrlPrefix;
            var currentBannermap = eDataContext.BannerMenuMaps.Where(e => e.BannerID == id).SingleOrDefault();
            var currentPossition = eDataContext.Positions.Where(e => e.ID == currentBannermap.PositionID).SingleOrDefault();
            var currentMenu = eDataContext.Menus.Where(e => e.ID == currentBannermap.MenuID).SingleOrDefault(); 
            return View(new BannerEditViewModel()
            {
                Banner = banner,
                currentMenus = currentMenu,
                currentPosition = currentPossition,
                ImageRootUrl = imgRootUrl,
                FlashRootUrl = flashRootUrl
            });
        }
        #endregion

        #region GET: /Banner/Create

        public ActionResult Create()
        {
            var menus = eDataContext.Menus.ToList();
            var position = eDataContext.Positions.ToList();
            var pubs = Utils.StringToDictionary(Settings.Default.BannerPubStatus.ToString(), ",");
            var languagecode = Utils.StringToDictionary(Settings.Default.LanguageCode.ToString(), ",");
            return View(new BannerEditViewModel()
            {
                Menus = menus,
                Positions = position,
                LanguageCode = languagecode
            });
        }
        #endregion

        #region POST: /Banner/Create
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(BannerEditViewModel a)
        {
            try
            {
                // TODO: Add insert logic here
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                a.Banner.Priority = Convert.ToInt32(Request["Priority"]); 
                a.Banner.FromDate = Request["FromDate"] != null ? Utils.ParseDateTime(Request["FromDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
                a.Banner.ToDate = Request["ToDate"] != null ? Utils.ParseDateTime(Request["ToDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
                a.Banner.AddDate = DateTime.Now;
                a.Banner.AddBy = UserManager.GetUserId();
                a.Banner.nClick = 0;
                UpdateModel(a);
                eDataContext.Banners.InsertOnSubmit(a.Banner);
                eDataContext.SubmitChanges();
                //Upload Image banner 
                HttpPostedFileBase fileImage = Request.Files["bannerImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    a.Banner.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.BannerImageRootPath), "" + a.Banner.ID);
                }

                // Upload Flash bannner
                HttpPostedFileBase fileFlash = Request.Files["bannerFlash"];
                if (fileFlash != null && fileFlash.ContentLength > 0)
                {
                    a.Banner.FlashPath = Path.GetFileName(fileFlash.FileName);
                    Uploads.UploadFile(fileFlash, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.BannerFlashRootPath), "" + a.Banner.ID);
                }
                eDataContext.SubmitChanges();
                var positionid = Request["PositionID"] != string.Empty ? Convert.ToInt32(Request["PositionID"].ToString()) : 0;
                // Insert table BannerMenuMap
                var menus = eDataContext.Menus.ToList();
                if (menus != null)
                {
                    foreach (var m in menus)
                    {
                        var isSelected = Request["chkMenu" + m.ID] != null &&
                            Request["chkMenu" + m.ID].ToString().Equals("false") == false ? true : false;
                        if (isSelected == true)
                        {
                            var bannerMenuMap = new BannerMenuMap();
                            bannerMenuMap.BannerID = a.Banner.ID;
                            bannerMenuMap.MenuID = m.ID;
                            bannerMenuMap.PositionID = positionid;
                            eDataContext.BannerMenuMaps.InsertOnSubmit(bannerMenuMap);
                            eDataContext.SubmitChanges();
                        }
                    }
                }
                
                eDataContext.SubmitChanges();

                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Banner/Edit/5

        public ActionResult Edit(int id)
        {
            //var currentMenus = eDataContext.BannerMenuMaps.Where(e => e.BannerID == id).SingleOrDefault();
            var currentPosition = eDataContext.BannerMenuMaps.Where(e => e.BannerID == id).FirstOrDefault();

            //var cm = currentMenus == null ? null : eDataContext.Menus.Where(e => e.ID == currentMenus.MenuID).SingleOrDefault();
            var cp = currentPosition == null ? null : eDataContext.Positions.Where(e => e.ID == currentPosition.PositionID).SingleOrDefault();
            
            var banner = eDataContext.Banners.Where(a => a.ID == id).SingleOrDefault();
            var menu = eDataContext.Menus.ToList();
            var positon = eDataContext.Positions.ToList();
            var languagecod = Utils.StringToDictionary(Settings.Default.LanguageCode.ToString(),",");
            return View(new BannerEditViewModel
            {
                Banner = banner,
                Menus = menu,
                Positions = positon,
                //currentMenus = cm,
                currentPosition = cp,
                LanguageCode = languagecod,
                ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.BannerImagePreviewUrlPrefix,
                FlashRootUrl = Settings.Default.SiteRootUrl + Settings.Default.BannerFlashPreviewUrlPrefix
            });
        }
        #endregion

        #region POST: /Banner/Edit/5
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, BannerEditViewModel a)
        {
            try
            {
                // Create new transaction
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                // TODO: Add update logic here                
                a.Banner = eDataContext.Banners.Where(e => e.ID == id).SingleOrDefault();
                a.Banner.Priority = Utils.ParseInt(Request["Pri"].ToString());
                a.Banner.ModifyBy = UserManager.GetUserId();
                a.Banner.ModifyDate = DateTime.Now;
                UpdateModel(a);

                a.Banner.FromDate = Request["FromDate"] != null ? Utils.ParseDateTime(Request["FromDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
                a.Banner.ToDate = Request["ToDate"] != null ? Utils.ParseDateTime(Request["ToDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
                a.Banner = eDataContext.Banners.Where(ar => ar.ID == id).SingleOrDefault();
                // Upload image banner
                HttpPostedFileBase fileImage = Request.Files["bannerImage"];
                if (fileImage != null && fileImage.FileName.Length > 0)
                {
                    //Delete old image
                    if (!string.IsNullOrEmpty(a.Banner.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.BannerImageRootPath, "" + a.Banner.ID + "_" + a.Banner.ImagePath)))
                        Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.BannerImageRootPath, "" + a.Banner.ID + "_" + a.Banner.ImagePath));

                    //DO upload new image banner
                    a.Banner.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.BannerImageRootPath), "" + a.Banner.ID);

                }
                // Upload file flash of banner
                HttpPostedFileBase fileFlash = Request.Files["bannerFlash"];
                if (fileFlash != null && fileFlash.FileName.Length > 0)
                {
                    //Delete old file flash
                    if (!string.IsNullOrEmpty(a.Banner.FlashPath) && System.IO.File.Exists(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.BannerFlashRootPath, "" + a.Banner.ID + "_" + a.Banner.FlashPath)))
                        Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.BannerFlashRootPath, "" + a.Banner.ID + "_" + a.Banner.FlashPath));

                    //DO upload new flash banner
                    a.Banner.FlashPath = Path.GetFileName(fileFlash.FileName);
                    Uploads.UploadFile(fileFlash, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.BannerFlashRootPath), "" + a.Banner.ID);
                }

                eDataContext.SubmitChanges();

                // Delete old BannerMenuMaps
                var currentbanner = eDataContext.BannerMenuMaps.Where(e => e.BannerID == id);

                eDataContext.BannerMenuMaps.DeleteAllOnSubmit(currentbanner);
                eDataContext.SubmitChanges();

                // Isert new BannerMenuMaps
                var positionid = Request["PostionID"] != string.Empty ? Convert.ToInt32(Request["PositionID"].ToString()) : 0;
                // Insert table BannerMenuMap
                var menus = eDataContext.Menus.ToList();
                if (menus != null)
                {
                    foreach (var m in menus)
                    {
                        var isSelected = Request["chkMenu" + m.ID] != null &&
                            Request["chkMenu" + m.ID].ToString().Equals("false") == false ? true : false;
                        if (isSelected == true)
                        {
                            var bannerMenuMap = new BannerMenuMap();
                            bannerMenuMap.BannerID = a.Banner.ID;
                            bannerMenuMap.MenuID = m.ID;
                            bannerMenuMap.PositionID = positionid;
                            eDataContext.BannerMenuMaps.InsertOnSubmit(bannerMenuMap);
                            eDataContext.SubmitChanges();
                        }
                    }
                }
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Banner/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Banners.Single(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Banner/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    var item = eDataContext.Banners.Single(e => e.ID == id);
                    if (item != null)
                    {
                        // Delete file image of banner
                        Uploads.DeleteFile(string.Format("{0}{1}{2}", Settings.Default.SiteRootPath, Settings.Default.BannerImageRootPath, item.ImagePath));
                        // Delete file flash of banner
                        Uploads.DeleteFile(string.Format("{0}{1}{2}", Settings.Default.SiteRootPath, Settings.Default.BannerFlashRootPath, item.FlashPath));
                        // Delete BannerMenuMap
                        var bannerMenuMap = eDataContext.BannerMenuMaps.Where(e => e.BannerID == id);
                        eDataContext.BannerMenuMaps.DeleteAllOnSubmit(bannerMenuMap);
                        eDataContext.SubmitChanges();
                        // Delete current banner
                        eDataContext.Banners.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

    }
}
